import 'package:changxindianzishangwu/dao/save_some_message_dao.dart';
import 'package:changxindianzishangwu/db/ec_cache.dart';
import 'package:changxindianzishangwu/model/group_message_list_model.dart';
import 'package:changxindianzishangwu/pages/my/settings/chat_management_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/privacy_setting_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/send_some_message_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/storage_management_page.dart';
import 'package:changxindianzishangwu/pages/my/settings/user_count_safe.dart';
import 'package:changxindianzishangwu/provider/conversion.dart';
import 'package:changxindianzishangwu/provider/currentMessageList.dart';
import 'package:changxindianzishangwu/provider/friend.dart';
import 'package:changxindianzishangwu/provider/friendApplication.dart';
import 'package:changxindianzishangwu/provider/groupApplication.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

import 'about_us_page.dart';

class SettingsPage extends StatefulWidget {
  SettingsPage({Key key}) : super(key: key);

  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  var sex;
  var _lights = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TopAppBar(context, "设置"),
      body: Column(
        children: [
          Container(
            alignment: Alignment.center,
            color: Colors.white,
            margin: EdgeInsets.only(top: 10),
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    //todo头像跳转
                    Get.to(() => UserCountSafe());
                  },
                  child: ListTile(
                    leading: Text(
                      "账号安全",
                      style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                    ),
                    title: Container(
                      alignment: Alignment.centerRight,
                      margin: EdgeInsets.only(left: 244),
                      height: ScreenUtil().setHeight(50),
                      width: ScreenUtil().setWidth(50),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(4),
                      ),
                    ),
                    trailing: Icon(Icons.keyboard_arrow_right),
                  ),
                ),
                Divider(
                  height: 1,
                  indent: ScreenUtil().setWidth(10),
                  color: Color.fromRGBO(248, 248, 248, 1),
                  thickness: ScreenUtil().setHeight(1),
                ),
                InkWell(
                  onTap: () {
                    Get.to(() => PrivacySettingPage());
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: ListTile(
                      leading: Text(
                        "隐私设置",
                        style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                      ),
                      title: Container(
                        alignment: Alignment.centerRight,
                        height: ScreenUtil().setHeight(50),
                        width: ScreenUtil().setWidth(50),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                        ),
                      ),
                      trailing: Icon(Icons.keyboard_arrow_right),
                    ),
                  ),
                ),
                Divider(
                  height: 1,
                  indent: ScreenUtil().setWidth(10),
                  color: Color.fromRGBO(248, 248, 248, 1),
                  thickness: ScreenUtil().setHeight(1),
                ),
                MergeSemantics(
                  child: ListTile(
                    title: Text(
                      '消息通知',
                      style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                    ),
                    trailing: CupertinoSwitch(
                      activeColor: Color.fromRGBO(0, 220, 169, 1),
                      value: _lights,
                      onChanged: (bool value) {
                        setState(() {
                          _lights = value;
                        });
                      },
                    ),
                    onTap: () {
                      setState(() {
                        _lights = !_lights;
                      });
                    },
                  ),
                ),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 11),
            color: Colors.white,
            child: InkWell(
              onTap: () {
                Get.to(SendSomeMessagePage(someMessageModel: someMessageModel));
              },
              child: ListTile(
                leading: Text(
                  "群发助手",
                  style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                ),
                title: Container(
                  alignment: Alignment.centerRight,
                  height: ScreenUtil().setHeight(50),
                  width: ScreenUtil().setWidth(50),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                trailing: Icon(Icons.keyboard_arrow_right),
              ),
            ),
          ),
          Container(
              alignment: Alignment.center,
              color: Colors.white,
              margin: EdgeInsets.only(top: 10),
              child: Column(
                children: <Widget>[
                  InkWell(
                    onTap: () {
                      Get.to(() => ChatManagementPage());
                    },
                    child: ListTile(
                      leading: Text(
                        "聊天管理",
                        style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                      ),
                      title: Container(
                        height: ScreenUtil().setHeight(50),
                        width: ScreenUtil().setWidth(50),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4),
                        ),
                      ),
                      trailing: Icon(Icons.keyboard_arrow_right),
                    ),
                  ),
                  Divider(
                    height: 1,
                    indent: ScreenUtil().setWidth(10),
                    color: Color.fromRGBO(248, 248, 248, 1),
                    thickness: ScreenUtil().setHeight(1),
                  ),
                  InkWell(
                    onTap: () {
                      Get.to(() => StorageManagementPage());
                    },
                    child: Container(
                      alignment: Alignment.center,
                      child: ListTile(
                        leading: Text(
                          "存储管理",
                          style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                        ),
                        title: Container(
                          height: ScreenUtil().setHeight(50),
                          width: ScreenUtil().setWidth(50),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(4),
                          ),
                        ),
                        trailing: Icon(Icons.keyboard_arrow_right),
                      ),
                    ),
                  ),
                  Divider(
                    height: 1,
                    indent: ScreenUtil().setWidth(10),
                    color: Color.fromRGBO(248, 248, 248, 1),
                    thickness: ScreenUtil().setHeight(1),
                  ),
                  InkWell(
                    onTap: () {
                      Get.to(() => AboutUsPage());
                    },
                    child: Container(
                      alignment: Alignment.center,
                      child: ListTile(
                        leading: Text(
                          "关于我们",
                          style: TextStyle(fontSize: ScreenUtil().setSp(15)),
                        ),
                        title: Container(
                          height: ScreenUtil().setHeight(50),
                          width: ScreenUtil().setWidth(50),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(4),
                          ),
                        ),
                        trailing: Icon(Icons.keyboard_arrow_right),
                      ),
                    ),
                  ),
                ],
              )),
          Container(
            alignment: Alignment.center,
            color: Colors.white,
            margin: EdgeInsets.only(top: ScreenUtil().setHeight(10)),
            child: InkWell(
              onTap: () {
                showCupertinoDialog(
                    context: context, builder: (context) => getDialog(context));
              },
              child: ListTile(
                title: Container(
                  alignment: Alignment.center,
                  height: ScreenUtil().setHeight(50),
                  width: ScreenUtil().setWidth(50),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    "退出登录",
                    style: TextStyle(
                        color: Colors.red, fontSize: ScreenUtil().setSp(14)),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  void onKickedOffline() async {
    TencentImSDKPlugin.v2TIMManager.logout();
// 被踢下线
    // 清除本地缓存，回到登录页TODO
    try {
      Provider.of<ConversionModel>(context, listen: false).clear();
      Provider.of<UserModel>(context, listen: false).clear();
      Provider.of<CurrentMessageListModel>(context, listen: false).clear();
      Provider.of<FriendListModel>(context, listen: false).clear();
      Provider.of<FriendApplicationModel>(context, listen: false).clear();
      Provider.of<GroupApplicationModel>(context, listen: false).clear();
      // 去掉存的一些数据
      Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
      SharedPreferences prefs = await _prefs;
      prefs.remove('token');
      prefs.remove('sessionId');
      prefs.remove('phone');
      prefs.remove('code');
    } catch (err) {
      print("someError");
      print(err);
    }
    print("被踢下线了");
  }

  GroupMessageListModel someMessageModel;

  /// 加载当前登录用户信息
  _loadUserInfo() async {
    await TencentImSDKPlugin.v2TIMManager.getLoginUser().then((value) async {
      await TencentImSDKPlugin.v2TIMManager
          .getUsersInfo(userIDList: [value.data]).then((values) async {
        someMessageModel = await SaveSomeMessageDao.querySomeMessages(
            userId: values.data[0].userID);
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _loadUserInfo();
  }

  CupertinoAlertDialog getDialog(context) {
    return CupertinoAlertDialog(
        content: new SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text(
                "退出登录",
                style: TextStyle(fontSize: 13, color: Colors.red),
              ),
              Text(
                "是否确定退出登录？",
                style:
                    TextStyle(fontSize: 13, color: AppColor.colorDefaultText),
              ),
            ],
          ),
        ),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text("确定"),
            onPressed: () {
              Navigator.of(context).pop();
              EcCache.getInstance().clear();
              onKickedOffline();
              Get.offAllNamed("/loginInit");
            },
          ),
          CupertinoDialogAction(
            child: Text("取消"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ]);
  }
}
